package com.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: oleksandr.baglai
 * Date: 11/10/12
 * Time: 7:45 PM
 */
public class CommandParser {
    private static Pattern pattern = Pattern.compile("((left)=(-?\\d*))|((right)=(-?\\d*))|((rotate)=(-?\\d*))|(drop)", Pattern.CASE_INSENSITIVE);

    private int left;
    private int right;
    private boolean drop;
    private int rotate;

    private String commandString;

    public CommandParser(String commandString) {
        this.commandString = commandString;
    }

    public void execute() {
        Matcher matcher = pattern.matcher(commandString);
        while (matcher.find()) {
            int groupsCount = matcher.groupCount();
            for (int i = 0; i <= groupsCount; i++) {
                String group = matcher.group(i);
                if (null == group) {
                    continue;
                }
                if (recognizeCommand(matcher, i, group)) {
                    break;
                }
            }
        }
    }


    private boolean recognizeCommand(Matcher matcher, int i, String group) {
        try {
            switch (group.toLowerCase()) {
                case "left":
                    left = Integer.parseInt(matcher.group(i + 1));
                    return true;
                case "right":
                    right = Integer.parseInt(matcher.group(i + 1));
                    return true;
                case "rotate":
                    rotate = Integer.parseInt(matcher.group(i + 1));
                    return true;
                case "drop":
                    drop = true;
                    return true;
            }
        } catch (NumberFormatException e) {
        }
        return false;
    }


    public int getLeft() {
        return left;
    }

    public int getRight() {
        return right;
    }

    public boolean isDrop() {
        return drop;
    }

    public int getRotate() {
        return rotate;
    }
}